// CommandLine.cpp
// (c) 2011, Charles Lechasseur
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "stdafx.h"
#include "CommandLine.h"


namespace RG64
{
    //
    // Constructor. Parses the command-line and fills in
    // our various fields.
    //
    // @param p_pCmdLine Command-line received by WinMain.
    //
    CommandLine::CommandLine(const char* const p_pCmdLine)
        : m_CmdLine(p_pCmdLine),
          m_DllName(),
          m_RegServerFlag(RegServer),
          m_InstallFlag(NoInstall),
          m_UnregFlag(false),
          m_InstallCmdLine(),
          m_Silent(false),
          m_Complete(false)
    {
        // Scan command-line to find flags.
        std::string cmdLine(p_pCmdLine);
        std::string::const_iterator lineIt, lineEnd = cmdLine.end();
        for (lineIt = cmdLine.begin(); lineIt != lineEnd; ) {
            // Skip whitespace.
            while (lineIt != lineEnd && (*lineIt == ' ' || *lineIt == '\t')) {
                ++lineIt;
            }

            if (lineIt != lineEnd) {
                if (*lineIt == '/') {
                    // This is a flag, read its value.
                    wchar_t flag = '\0';
                    if (++lineIt != lineEnd) {
                        flag = *lineIt++;
                    }
                    switch (flag) {
                        case 'u':
                        case 'U': {
                            // Call UnregServer instead of Reg.
                            // If we're supposed to call DllInstall, instead call Uninstall.
                            m_UnregFlag = true;
                            if (m_RegServerFlag != NoRegServer) {
                                m_RegServerFlag = UnRegServer;
                            }
                            if (m_InstallFlag != NoInstall) {
                                m_InstallFlag = Uninstall;
                            }
                            break;
                        }
                        case 's':
                        case 'S': {
                            // Run in silent mode.
                            m_Silent = true;
                            break;
                        }
                        case 'i':
                        case 'I': {
                            // Call DllInstall with optional command-line.
                            if (!m_UnregFlag) {
                                m_InstallFlag = Install;
                            } else {
                                m_InstallFlag = Uninstall;
                            }
                            if (lineIt != lineEnd && *lineIt == ':') {
                                // Check whether we have quotes. If so, skip to next quotes;
                                // if not, skip to next whitespace.
                                std::string::const_iterator cmdLineEnd = ++lineIt;
                                if (cmdLineEnd != lineEnd) {
                                    if (*cmdLineEnd == '"') {
                                        ++lineIt, ++cmdLineEnd;
                                        while (cmdLineEnd != lineEnd && *cmdLineEnd != '"') {
                                            ++cmdLineEnd;
                                        }
                                    } else {
                                        while (cmdLineEnd != lineEnd && *cmdLineEnd != ' ' && *cmdLineEnd != '\t') {
                                            ++cmdLineEnd;
                                        }
                                    }
                                    SetInstallCmdLine(std::string(lineIt, cmdLineEnd));
                                    lineIt = cmdLineEnd;
                                    if (lineIt != lineEnd && *lineIt == '"') {
                                        ++lineIt;
                                    }
                                }
                            }
                            break;
                        }
                        case 'n':
                        case 'N': {
                            // Do not call DllReg/UnregServer.
                            m_RegServerFlag = NoRegServer;
                            break;
                        }
                        default:
                            // This is not a value flag. Break out of the loop; command-line is invalid.
                            lineIt = lineEnd;
                    }
                } else {
                    // This means we're at the beginning of the DLL name. Everything else
                    // is part of that name. There's a single name, so remove quotes if we have them.
                    if (*lineIt == '"') {
                        ++lineIt;
                    }
                    if (lineIt != lineEnd && *(lineEnd - 1) == '"') {
                        --lineEnd;
                    }
                    m_DllName.assign(lineIt, lineEnd);

                    // Command-line is now complete if we have a DLL name.
                    m_Complete = !m_DllName.empty();
                    lineIt = lineEnd;
                }
            }
        }
    }

    //
    // Sets the m_InstallCmdLine from a multi-byte string.
    // The install command-line needs to be a unicode string.
    //
    // @param p_CmdLine Install command-line to set.
    //
    void CommandLine::SetInstallCmdLine(const std::string& p_CmdLine)
    {
        // First get required buffer size.
        int bufSize = ::MultiByteToWideChar(CP_ACP,
                                            MB_PRECOMPOSED,
                                            p_CmdLine.c_str(),
                                            -1,
                                            0,
                                            0);

        // Allocate buffer and call again to get the unicode version.
        LPWSTR pBuffer = new WCHAR[bufSize];
        int written = ::MultiByteToWideChar(CP_ACP,
                                            MB_PRECOMPOSED,
                                            p_CmdLine.c_str(),
                                            -1,
                                            pBuffer,
                                            bufSize);

        // Copy buffer to our member and free it.
        m_InstallCmdLine = pBuffer;
        delete [] pBuffer;
    }

} // namespace RG64
